package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

/**
 * 密码验证Activity
 * 在禁用时间段内弹出，要求输入密码才能使用
 */
public class PasswordVerifyActivity extends AppCompatActivity {

    private ParentalControlRepository repository;
    private BlockTimeChecker blockTimeChecker;
    
    private TextView textTitle;
    private TextView textMessage;
    private StringBuilder password;
    private View[] dots;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_password_verify);

        repository = ParentalControlRepository.getInstance(this);
        blockTimeChecker = new BlockTimeChecker(this);

        initViews();
        setupListeners();
        updateMessage();
    }

    private void initViews() {
        textTitle = findViewById(R.id.text_verify_title);
        textMessage = findViewById(R.id.text_verify_message);
        password = new StringBuilder();
        
        dots = new View[]{
            findViewById(R.id.dot1),
            findViewById(R.id.dot2),
            findViewById(R.id.dot3),
            findViewById(R.id.dot4)
        };
        
        // 设置标题
        textTitle.setText("输入密码");
    }

    private void updateMessage() {
        BlockTimeSlot slot = blockTimeChecker.getCurrentBlockedSlot();
        if (slot != null) {
            int remainingMinutes = blockTimeChecker.getRemainingBlockMinutes();
            textMessage.setText(String.format(
                "处于禁用时间段 %s（还剩 %d 分钟）",
                slot.getTimeRangeText(),
                remainingMinutes
            ));
        } else {
            textMessage.setText("输入密码启用智能控制");
        }
    }

    private void setupListeners() {
        View.OnClickListener numberListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (password.length() < 4) {
                    Button btn = (Button) v;
                    password.append(btn.getText());
                    updatePasswordDots(password.length());
                    
                    if (password.length() == 4) {
                        verifyPassword();
                    }
                }
            }
        };

        findViewById(R.id.btn_0).setOnClickListener(numberListener);
        findViewById(R.id.btn_1).setOnClickListener(numberListener);
        findViewById(R.id.btn_2).setOnClickListener(numberListener);
        findViewById(R.id.btn_3).setOnClickListener(numberListener);
        findViewById(R.id.btn_4).setOnClickListener(numberListener);
        findViewById(R.id.btn_5).setOnClickListener(numberListener);
        findViewById(R.id.btn_6).setOnClickListener(numberListener);
        findViewById(R.id.btn_7).setOnClickListener(numberListener);
        findViewById(R.id.btn_8).setOnClickListener(numberListener);
        findViewById(R.id.btn_9).setOnClickListener(numberListener);

        findViewById(R.id.btn_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (password.length() > 0) {
                    password.deleteCharAt(password.length() - 1);
                    updatePasswordDots(password.length());
                }
            }
        });
    }

    private void updatePasswordDots(int count) {
        for (int i = 0; i < dots.length; i++) {
            if (i < count) {
                dots[i].setBackgroundResource(R.drawable.password_dot_filled);
            } else {
                dots[i].setBackgroundResource(R.drawable.password_dot_empty);
            }
        }
    }

    private void verifyPassword() {
        String savedPassword = repository.getPassword();
        
        if (savedPassword == null || savedPassword.isEmpty()) {
            // 未设置密码，直接通过并设置临时解锁状态
            Toast.makeText(this, "未设置密码，已解锁", Toast.LENGTH_SHORT).show();
            repository.setTemporarilyUnlocked(true);
            finish();
            return;
        }

        if (password.toString().equals(savedPassword)) {
            // 密码正确
            Toast.makeText(this, "密码正确，已解锁", Toast.LENGTH_SHORT).show();
            
            // 记录临时解锁状态（可选：设置一个时间限制）
            repository.setTemporarilyUnlocked(true);
            
            finish();
        } else {
            // 密码错误
            Toast.makeText(this, "密码错误，请重新输入", Toast.LENGTH_SHORT).show();
            password.setLength(0);
            updatePasswordDots(0);
        }
    }

    @Override
    public void onBackPressed() {
        // 禁用返回键，防止绕过密码验证
        Toast.makeText(this, "请输入密码解锁", Toast.LENGTH_SHORT).show();
    }
}

